package com.zlx.store.coupon.aspect;

import com.zlx.store.common.results.HttpResp;
import com.zlx.store.common.results.RespCode;
import com.zlx.store.coupon.constants.RabbitMQConstants;
import com.zlx.store.domain.entity.LogMessage;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Aspect
@Component
public class LoggingAspect {

    //一般来说抢完券之后的半个小时内,是服务器的请求高峰,这时候不对数据库进行操作,所以设置延时时间为半个小时
    final int DELAY_SECONDS = 30*60*1000;
    //final int DELAY_SECONDS = 10*1000;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 抢票日志
     * @param joinPoint
     */
    @Around("execution(* com.zlx.store.coupon.service.CouponService.snapUpCoupon(..))")
    public Object snapUpCouponLog(ProceedingJoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        LogMessage logMessage = new LogMessage();
        if (args[0] != null) {
            logMessage.setCouponId(args[0].toString());
        }
        if (args[1] != null) {
            logMessage.setUserId(args[1].toString());
        }

        Object result = null;

        try {
            result = joinPoint.proceed();
            if (result instanceof HttpResp) {
                logMessage.setHttpResp((HttpResp) result);
            }
            return result;

        } catch (Throwable e) {
            logMessage.setHttpResp(new HttpResp(RespCode.USER_OPERATION_ERROR,"日志记录错误", new Date()));
            throw new RuntimeException(e);
        } finally {
            //将对象写入到延时队列中
            rabbitTemplate.convertAndSend(
                    RabbitMQConstants.DELAY_EXCHANGE,
                    RabbitMQConstants.DELAY_ROUTING_KEY,
                    logMessage,
                    message->{
                        //mpp.getMessageProperties().setExpiration(String.valueOf(DELAY_SECONDS));
                        message.getMessageProperties().setHeader("x-delay",DELAY_SECONDS);
                        return message;
                    });
        }
    }
}
